﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.IO.IsolatedStorage;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using RadarGlobalPro.Class;
using Microsoft.Phone.Net.NetworkInformation;

namespace RadarGlobalPro.GUIView
{
    public partial class LoginDlg : PhoneApplicationPage
    {
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

        Status status = new Status();

        private double _dragDistanceToOpen = 75.0;
        private double _dragDistanceToClose = 305.0;
        private double _dragDistanceNegative = -75.0;

        private FrameworkElement _feContainer;

        private bool _isSettingsOpen = false;

        public LoginDlg()
        {
            InitializeComponent();

            _feContainer = this.LayoutRoot as FrameworkElement;
        }

        #region Control Event
        private void cmdRegister_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //NavigationService.Navigate(new Uri("/GUIView/RegisterDlg.xaml", UriKind.Relative));
            OpenSettings();
            _isSettingsOpen = true;
        }
        private void cmdLogin_Click(object sender, RoutedEventArgs e)
        {
            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.CheckLoginCompleted += (s, args) =>
            {
                status.Remove();

                if (args==null || args.Result == "false")
                {

                    MessageBox.Show("Please check username or password and try again..!", "Fail login", MessageBoxButton.OK);
                }
                else
                {
                    MessageBox.Show("You login sucess ! welcom to global radar application", "Login success!", MessageBoxButton.OK);

                    Global.UserInfo = JsonConvert.DeserializeObject<User>(args.Result);

                    if (settings.Contains("Login"))

                        settings["Login"] = true;

                    else

                        settings.Add("Login", true);

                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
                }

            };

            client.CheckLoginAsync(txtUsername.Text, txtPassword.Password.ToString());

            status.ShowPopup("Please wait! checking connect server...");
        }
        private void cmdCancel_Click(object sender, RoutedEventArgs e)
        {
            CloseSettings();
            _isSettingsOpen = false;
        }
        private void cmdRegisterUser_Click(object sender, RoutedEventArgs e)
        {
            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Can't connect database , Please check wifi/cellular data...");

                return;
            }
            if (txtRegUsername.Text == "") { MessageBox.Show("Please input username!", "Error", MessageBoxButton.OK); return; }
            if (txtRegPassword.Password != txtRePassword.Password) { MessageBox.Show("Password are not the same!", "Error", MessageBoxButton.OK); return; }
            if (txtFullname.Text == "") { MessageBox.Show("Please input fullname", "Error", MessageBoxButton.OK); return; }
            status.ShowPopup("Please wait response by server...!");
            client.ExistsUserAsync(txtRegUsername.Text);
            client.ExistsUserCompleted += (s, args) =>
            {
                status.Abort();
                if (args.Result ==false)
                {
                    client.CreateUserCompleted += (obj, arg) =>
                    {
                        if (arg.Result == true)
                        {
                            MessageBox.Show("Register user sucess!!", "welcom application", MessageBoxButton.OK);
                            //NavigationService.Navigate(new Uri("/UIView/LoginDlg.xaml", UriKind.RelativeOrAbsolute));
                            CloseSettings();
                            _isSettingsOpen = false;
                        }
                        else
                            MessageBox.Show("Your account already exists! Please try again", "Error", MessageBoxButton.OK);
                    };
                    client.CreateUserAsync(txtRegUsername.Text, txtRegPassword.Password.ToString(), txtFullname.Text, txtEmail.Text, 1, 1);
                }
                else
                    MessageBox.Show("User is Exsits!", "Register Error!", MessageBoxButton.OK);
            };            
        }
        #endregion

        #region Config Event LostFocus and GotFocus
        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox myTextBox = (sender as TextBox);

            if(myTextBox!=null)
                
                myTextBox.Opacity = 1;

            if(myTextBox.Text=="Username")
            
                myTextBox.Text = "";
            
        }
        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox myTextBox = (sender as TextBox);

            if (myTextBox != null)

                myTextBox.Opacity = 0.5;

            if (myTextBox.Tag!=null && myTextBox.Tag.ToString() == "uname" && myTextBox.Text == "")

                myTextBox.Text = "Username";
        }
        private void PasswordBox_GotFocus(object sender, RoutedEventArgs e)
        {
            PasswordBox myPasswordBox = (sender as PasswordBox);

            if (myPasswordBox != null)

                myPasswordBox.Opacity = 1;

            if (myPasswordBox.Password == "Password")

                myPasswordBox.Password = "";
        }
        private void PasswordBox_LostFocus(object sender, RoutedEventArgs e)
        {
            PasswordBox myPasswordBox = (sender as PasswordBox);

            if (myPasswordBox != null)

                myPasswordBox.Opacity = 0.5;

            if (myPasswordBox.Tag!=null &&myPasswordBox.Tag.ToString() == "password" && myPasswordBox.Password == "")

                myPasswordBox.Password = "Password";
            
        }
        #endregion

        #region Animiation For Register Dialog
        private void CloseSettings()
        {
            var trans = _feContainer.GetVerticalOffset().Transform;
            trans.Animate(trans.Y, 0, TranslateTransform.YProperty, 500, 0, new CubicEase
            {
                EasingMode = EasingMode.EaseOut
            });

            _isSettingsOpen = false;
        }

        private void OpenSettings()
        {
            var trans = _feContainer.GetVerticalOffset().Transform;
            trans.Animate(trans.Y, 750.0, TranslateTransform.YProperty, 500, 0, new CubicEase
            {
                EasingMode = EasingMode.EaseOut
            });

            _isSettingsOpen = true;
        }

        private void GestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Vertical && e.VerticalChange > 0 && !_isSettingsOpen)
            {
                double offset = _feContainer.GetVerticalOffset().Value + e.VerticalChange;
                if (offset > _dragDistanceToOpen)
                    this.OpenSettings();
                else
                    _feContainer.SetVerticalOffset(offset);
            }

            if (e.Direction == System.Windows.Controls.Orientation.Vertical && e.VerticalChange < 0 && _isSettingsOpen)
            {
                double offsetContainer = _feContainer.GetVerticalOffset().Value + e.VerticalChange;
                if (offsetContainer < _dragDistanceToClose)
                    this.CloseSettings();
                else
                    _feContainer.SetVerticalOffset(offsetContainer);
            }
        }

        private void GestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Vertical && e.VerticalChange > 0 && !_isSettingsOpen)
            {
                if (e.VerticalChange < _dragDistanceToOpen)
                    this.ResetLayoutRoot();
                else
                    this.OpenSettings();
            }

            if (e.Direction == System.Windows.Controls.Orientation.Vertical && e.VerticalChange< 0 && _isSettingsOpen)
            {
                if (e.VerticalChange > _dragDistanceNegative)
                    this.ResetLayoutRoot();
                else
                    this.CloseSettings();
            }
        }
        private void ResetLayoutRoot()
        {
            if (!_isSettingsOpen)
                _feContainer.SetVerticalOffset(0.0);
            else
                _feContainer.SetVerticalOffset(750.0);
        }
        #endregion
    }
}